var WeiSokect = function(config){
    var sokect = null;        //sokect对象
    var num = 0;              //sokect连接次数
    var timp = null;          //心跳定时器
    var heartbeat = 1;        //心跳状态  1正常  2死亡
    var heartbeatTimes = 15;  //心跳时间  秒
    function init(){
        var userToken = fox.storage.get('userToken');
        var userRole = fox.storage.get('userRole'); //1是用户 2 是客服
        var userId = fox.storage.get('userId');
        if(!userToken)return
        sokect = null;     
        sokect =  new WebSocket(config.url);
        sokect.onopen = function(){
            api.sendEvent({name:"sokectStateChange",extra:{state:1}})
            //绑定
            if(userRole == 1){
                var bindContent = {
                    event:"bind",
                    token:userToken,
                }
            }else{
                var bindContent = {
                    event:"bind",
                    user_id:0,
                }
            }
            sokect.send(JSON.stringify(bindContent));
            clearInterval(timp)
            //心跳
            timp = setInterval(function(){
                var state = sokect ? sokect.readyState : 2;
                if(state == 2 || state == 3 || state == undefined){
                    state = 2;
                } 
                if(state == 2){
                    sokect ? sokect.close() : ""; 
                    sokect = null;
                    init();
                    return false 
                }
                var sayContent = '{"event":"ping"}';
                api.sendEvent({name:"wsSendMsg",extra:{msg:sayContent}})
            }, 1000 * heartbeatTimes)
            //切换前台重新检测状态
            api.addEventListener({
                name:'resume'
            }, function(ret, err){  
                var state = sokect ? sokect.readyState : 2;
                if(state == 2 || state == 3 || state == undefined){
                    state = 2;
                }
                if(state == 2){
                    sokect ? sokect.close() : ""; 
                    sokect = null;
                    init();
                }
            });
        }
        sokect.onmessage = function(e){       //信息接收 25秒 0 =》 ping 1=》 pong 27秒终止心跳 
            console.log(e.data)
            var redata = JSON.parse(e.data);
            if(redata.type == 1 && redata.data && redata.data.user_id != userId){
                sendNoticeBar({
                    title:redata.data.user.nickname,
                    content:redata.data.content,
                    extra:{
                        roomId:redata.data.room_id,
                        pageTitle:redata.data.user.nickname,
                    }
                });
                api.addEventListener({name:"noticeclicked"},function(ret,err){
                    var dt = JSON.parse(ret.value);
                    fox.navigateTo({
                        url:"./html/libs_frame/chat_box?roomId="+dt.roomId+"&pageTitle="+dt.pageTitle
                    })
                })
            }
            if(redata.type){
                api.sendEvent({name:"acceptMsg",extra:{msg:redata}})
            }
        } 
        sokect.onerror = function(){   //出错
            num++
            if(num <= 5){
                api.sendEvent({name:"sokectStateChange",extra:{state:2}})
                fox.showToast({title:"聊天服务器连接失败~~"})
                sokect = null;
                //init();
            }
        }
        sokect.onclose = function(){  //关闭
            num++
            if(num <= 5){
                sokect = null;
                //init();
            }
        }
    }
    api.addEventListener({   //发送信息
        name: 'wsSendMsg'
    }, function(ret, err){
        try {
            sokect.send(ret.value.msg);
        } catch (error) {
            
        }
    });
    api.addEventListener({
        name:"wxClose",
    },function(ret,err){
        try {
            sokect ? sokect.close() : ""; 
            sokect = null;
            clearInterval(timp)
        } catch (error) {
            
        }
    })
    //读取webSokect状态 0正在连接  1 连接成功  2连接失败
    api.addEventListener({
        name:'readSokectState'
    },function(){
        var state = sokect ? sokect.readyState : 2;
        if(state == 2 || state == 3 || state == undefined){
            state = 2;
        }
        api.sendEvent({name:"sokectStateChange",extra:{state:state}})
    })
    //重新加载Sokect连接
    api.addEventListener({
        name:'initSokectState'
    },function(){
        var state = sokect ? sokect.readyState : 2;
        if(state == 2 || state == 3 || state == undefined){
            state = 2;
        }
        if(state == 2){
            sokect ? sokect.close() : ""; 
            sokect = null;
            init();
        }
    })
    init();
    fox.eventCenter.on('initSokect', function () {
        init();
    })
}